/*************************************************************************
*																		 *
*				code by Miles Chen (v-mich) 2007.10.8					 *
*																		 *
*																		 *
*************************************************************************/

#pragma once

#include "commdef-int.h"

namespace System{namespace Convert{

	double StringToDouble(LPCWSTR lpszString)
	{
		//TODO: 
		//return msvcrt_wtof(lpszString);
		return _wtof(lpszString);
	}

	void DoubleToString(LPWSTR lpszString, double p, int decimals)
	{
		//TODO: 
		//
		CHAR ansiBuffer[SHORT_CHAR];

		if(decimals == 2)
			sprintf(ansiBuffer, "%.2lf", p);
		else if(decimals == 0)
			sprintf(ansiBuffer, "%.0lf", p);
		else if(decimals == 3)
			sprintf(ansiBuffer, "%.3lf", p);
		else
			sprintf(ansiBuffer, "%lf", p);

		MultiByteToWideChar(CP_ACP, 0, ansiBuffer, -1, lpszString, SHORT_CHAR);
		//
	}

	int Hex2Int(unsigned short c)
	{
		if(c >= '0' && c<= '9')
			return c - 48;
		else if(c >= 'a' && c<= 'h')
			return c - 87;
		else if(c >= 'A' && c<= 'H')
			return c - 55;
		else
			return -1;
	}


	int StringToInt32(LPCWSTR lpszString)
	{
		int fSign;
		int value = 0;
		LPWSTR p = (LPWSTR)lpszString;

		if(String::StartWith(p, L"+"))
		{
			fSign = 1;
			p++;
		}
		else if(String::StartWith(p, L"-"))
		{
			fSign = -1;
			p++;
		}
		else
		{
			fSign = 1;
		}

		int len = String::Length(p);
		for(int i=len - 1; i>=0; i--)
		{
			value += Hex2Int(*(p + i)) * Math::Pow(10, len - i -1);
		}

		return value * fSign;
	}

	unsigned int HexStringToInt32(LPCWSTR lpszString)
	{
		unsigned int value = 0;
		LPWSTR p = (LPWSTR)lpszString;

		if(String::StartWith(p, L"0x") 
			|| String::StartWith(p, L"0X"))
		{
			p += 2;
		}

		int len = String::Length(p);
		for(int i=len - 1; i>=0; i--)
		{
			value += Hex2Int(*(p + i)) * Math::Pow(16, len - i -1);
		}

		return value;
	}
}}